import { loginAPI, getUserInfoAPI } from '@/api/user'
import { getToken, setToken, getUserInfo, setUserInfo } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    username: getUserInfo().username || '',
    password: getUserInfo().password || '',
    uuid: getUserInfo().uuid || '',
    userInfo: {}
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
      setToken(token)
    },
    SET_INFO(state, { username, password, uuid }) {
      state.username = username
      state.password = password
      state.uuid = uuid
      setUserInfo({ username, password, uuid })
    },
    SET_USERINFO(state, userInfo) {
      state.userInfo = userInfo
    }
  },
  actions: {
    async loginAction(ctx, { username, password }) {
      const res = await loginAPI({
        username,
        password
      })
      if (res.code === 10000) {
        ctx.commit('SET_TOKEN', res.data.token)
      }
    },
    logoutAction(ctx) {
      ctx.commit('SET_TOKEN', '')
      ctx.commit('SET_USERINFO', {})
    },
    async getUserInfoAction(ctx) {
      const res = await getUserInfoAPI()
      // const resDetail = await getUserDetailAPI(res.data.id)
      ctx.commit('SET_USERINFO', res.data)
    }
  },
  getters: {}
}
